﻿/*----------------------------------------------------------------
// Copyright (C) 2019 Emo-电子DIY工作坊
// 版权所有。
//
// 文件名：NetworkCardHelper.cs
// 功能描述：
// 
// 创建标识：Whble(Zengyun) 2019/6/22 18:06:10
// 
// 修改标识：
// 修改描述：
//
// 修改标识：
// 修改描述：
//
//----------------------------------------------------------------*/
using System.Collections.Generic;
using System.Management;
namespace TCP_Toos
{
    /// <summary>
    /// 网卡服务类
    /// </summary>
    public class NetworkCardHelper
    {
        /// <summary>
        /// 获取所有的网卡
        /// </summary>
        /// <returns></returns>
        public static List<string> GetAllConfigurationalleNetCard()
        {
            List<string> netCardList = new List<string>();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration ");
            foreach (ManagementObject obj2 in searcher.Get())
            {
                try
                {
                    if (obj2["IPAddress"] != null)
                    {
                        string str = obj2["Description"].ToString();
                        int index = str.IndexOf("-", 0);
                        if (index > 0)
                        {
                            netCardList.Add(str.Substring(0, index).Trim());
                        }
                        else
                        {
                            netCardList.Add(str.Trim());
                        }
                    }
                    else
                    {

                       // netCardList.Add(str.Trim());
                    }
                }
                catch
                {
                }
            }
            return netCardList;
        }
        /// <summary>
        /// 获取所有网卡的IP
        /// </summary>
        /// <returns></returns>
		public static List<string> GetAllConfigurationalleIp()
		{
			List<string> IpList = new List<string>();
			foreach (var nwCardName in GetAllConfigurationalleNetCard())
			{
				IpList.Add(GetConfiguraton(nwCardName).IPAddList[0]);
			}
			return IpList;
		}
        /// <summary>
        /// 获取所有网卡信息
        /// </summary>
        /// <returns></returns>
		public static List<CardInfo> GetAllNetWorkCardInfo()
		{
			List<CardInfo> infoList = new List<CardInfo>();
			foreach (var nwCardName in GetAllConfigurationalleNetCard())
			{
				infoList.Add(GetConfiguraton(nwCardName));
			}
			return infoList;
		}
        /// <summary>
        /// 网卡信息以字典方式查询
        /// </summary>
        /// <returns></returns>
		public static Dictionary<string, string> GetAllNetWorkCardDictionary()
		{
			Dictionary<string, string> dit = new Dictionary<string, string>();
			foreach (var nwCardName in GetAllConfigurationalleNetCard())
			{
				dit.Add(nwCardName, GetConfiguraton(nwCardName).IPAddList[0]);
			}
			return dit;
		}
        /// <summary>
        /// 获取网卡配置
        /// </summary>
        /// <param name="nwCardName"></param>
        /// <returns></returns>
		public static CardInfo GetConfiguraton(string nwCardName)
        {
            if (nwCardName.Length > 0)
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description like '" + nwCardName + "%'");
                foreach (ManagementObject obj2 in searcher.Get())
                {
                    try
                    {
						CardInfo cardInfo = new CardInfo();
						cardInfo.AutoDNS = false;
						cardInfo.IsDHCP = false;
						cardInfo.CarInfoName = nwCardName;

						string[] ipstr = obj2["IPAddress"] as string[];
                        string[] subnet = obj2["IPSubnet"] as string[];
                        string[] getway = obj2["DefaultIPGateway"] as string[];
                        string[] dns = obj2["DNSServerSearchOrder"] as string[];

                        if (ipstr != null)
                        {
							cardInfo.IPAddList.AddRange(ipstr);
                        }
                        if (subnet != null)
                        {
							cardInfo.Subnet.AddRange(subnet);
                        }
                        if (getway != null)
                        {
							cardInfo.Getway.AddRange(getway);
                        }
                        if (dns != null)
                        {
							cardInfo.DNS.AddRange(dns);
                        }
                        return cardInfo;
                    }
                    catch
                    {
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 修改DHCP
        /// </summary>
        /// <param name="nwCardName"></param>
        /// <returns></returns>
        public static bool SwitchToDHCP(string nwCardName)
        {
            ManagementBaseObject inParameters = null;
            ManagementBaseObject obj3 = null;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description like '" + nwCardName + "%'");
            foreach (ManagementObject obj4 in searcher.Get())
            {
                try
                {
                    if (!((bool)obj4["IPEnabled"]))
                    {
                        continue;
                    }
                    inParameters = obj4.GetMethodParameters("EnableDHCP");
                    obj3 = obj4.InvokeMethod("EnableDHCP", inParameters, null);
                    inParameters = obj4.GetMethodParameters("SetDNSServerSearchOrder");
                    obj3 = obj4.InvokeMethod("SetDNSServerSearchOrder", inParameters, null);
                    break;
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 修改Ip地址
        /// </summary>
        /// <param name="nwCardName"></param>
        /// <param name="carInfo"></param>
        /// <returns></returns>
        public static bool SwitchIPAddress(string nwCardName, CardInfo carInfo)
        {
            ManagementBaseObject methodParameters;
            ManagementBaseObject obj3;
            ManagementObjectSearcher searcher;
            methodParameters = null;
            obj3 = null;
            searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description like '" + nwCardName + "%'");
            foreach (ManagementObject obj4 in searcher.Get())
            {
                try
                {
                    if ((bool)obj4["IPEnabled"])
                    {
                        if (!carInfo.IsDHCP)
                        {
                            methodParameters = obj4.GetMethodParameters("EnableStatic");
                            methodParameters["IPAddress"] = carInfo.IPAddList.ToArray();
                            methodParameters["SubnetMask"] = carInfo.Subnet.ToArray();
                            obj3 = obj4.InvokeMethod("EnableStatic", methodParameters, null);
                            methodParameters = obj4.GetMethodParameters("SetGateways");
                            methodParameters["DefaultIPGateway"] = carInfo.Getway.ToArray();
                            obj3 = obj4.InvokeMethod("SetGateways", methodParameters, null);
                            methodParameters = obj4.GetMethodParameters("SetDNSServerSearchOrder");
                            methodParameters["DNSServerSearchOrder"] = carInfo.DNS.ToArray();
                            obj3 = obj4.InvokeMethod("SetDNSServerSearchOrder", methodParameters, null);
                            break;
                        }
                        else
                        {
                            methodParameters = obj4.GetMethodParameters("EnableDHCP");
                            obj3 = obj4.InvokeMethod("EnableDHCP", methodParameters, null);
                            if (carInfo.AutoDNS)
                            {
                                methodParameters = obj4.GetMethodParameters("SetDNSServerSearchOrder");
                                obj3 = obj4.InvokeMethod("SetDNSServerSearchOrder", methodParameters, null);
                            }
                            else
                            {
                                methodParameters = obj4.GetMethodParameters("SetDNSServerSearchOrder");
                                methodParameters["DNSServerSearchOrder"] = carInfo.DNS.ToArray();
                                obj3 = obj4.InvokeMethod("SetDNSServerSearchOrder", methodParameters, null);
                            }
                        }
                    }
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
    }
    /// <summary>
    /// 网卡信息类
    /// </summary>
    public class CardInfo
    {
        /// <summary>
        /// CardInfo
        /// </summary>
        public CardInfo()
        {
            IsDHCP = true;
            AutoDNS = true;
            IPAddList = new List<string>();
            Subnet = new List<string>();
            Getway = new List<string>();
            DNS = new List<string>();
        }
        /// <summary>
        /// 输出方法
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return CarInfoName;
        }
        /// <summary>
        /// 
        /// </summary>
        public bool IsDHCP
        {
            get;
            set;
        }
        /// <summary>
        /// 
        /// </summary>
        public string CarInfoName
		{
            get;
            set;
        }
        /// <summary>
        /// 获取和设置IP列表
        /// </summary>
        public List<string> IPAddList
        {
            get;
            set;
        }
        /// <summary>
        /// 获取和设置子网掩码
        /// </summary>
        public List<string> Subnet
        {
            get;
            set;
        }
        /// <summary>
        /// 获取和设置网关地址
        /// </summary>
        public List<string> Getway
        {
            get;
            set;
        }
        /// <summary>
        /// 
        /// </summary>
        public bool AutoDNS
        {
            get;
            set;
        }
        /// <summary>
        /// 获取和设置DNS地址
        /// </summary>
        public List<string> DNS
        {
            get;
            set;
        }
    }
}
